/**
 * Created by zhoulin on 2019/4/3.
 */
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);
var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);
var staffTmpId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.staffTmpId);

var E = window.wangEditor;
var editor = new E('#editor');

var app = new Vue({
    el: '#app',
    data: {
        permissions:['teacher:add','teacher:update'],//本页权限数组
        content:'',
        desc:'',
        experience:'',
        selects:[],
        schoolId:schoolId,
        schoolList:schoolMap,
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        that.getTagList();
        if(empty(token)){
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon:5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            },1200);

            return ;
        }

        if(!empty(aGET.id)){
            that.getInfoById(aGET.id);
        }
        if (!empty(staffTmpId)) {
            // 已选员工项
            that.getByStaff(staffTmpId);
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.staffTmpId,'');
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        getTagList: function () {
            var that = this;
            Get(that, _HOST + _API.common_tag_getTagsByType + "?type=3&companyId=" + companyId + "&schoolId=" + schoolId)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        initSelect(response.list);
                    }
                });
        },
        // 取得staff信息
        getByStaff: function(staffId) {
            var that = this;
            Get(that,_HOST+_API.organization_teacher_getByStaff+"?staffId="+staffId)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if(response){
                        if(response.success){
                            var list = response.data;
                            var oldImgId = "";
                            for (var item in list) {
                                if (item == 'imgId') {
                                    oldImgId = list[item];
                                }
                                if (item == 'showUrl') {
                                    initFileUpload(list[item]);
                                }
                                if (item == 'sex') {
                                    $("#Form select[name='sex']").val(list[item]);
                                }
                                $("#Form input[name='" + item + "']").val(list[item]);
                            }
                            $("#Form input[name='oldImgId']").val(oldImgId);
                            $("#Form").data('bootstrapValidator').destroy();
                            $('#Form').data('bootstrapValidator', null);
                            Validator();
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        selectStaff: function() {
            var that = this;
            var index = layer.open({
                type: 2,
                title: "选择员工",
                content: "staff.html",
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
            });
            layer.full(index);
        },
        getInfoById:function (id) {
            var that = this;
            Get(that,_HOST+_API.organization_teacher_getById+"?id="+id)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if(response){
                        if(response.success){
                            var list = response.data;
                            var oldImgId = "";
                            for (var item in list) {
                                if (item == 'imgId') {
                                    oldImgId = list[item];
                                }
                                if (item == 'shortDesc') {
                                    that.desc = list[item];
                                }
                                if (item == 'experience') {
                                    that.experience = list[item];
                                }
                                if (item == 'description') {
                                    editor.txt.html(list[item]);
                                }
                                if (item == 'showUrl') {
                                    initFileUpload(list[item]);
                                }
                                if (item == 'sex') {
                                    $("#Form select[name='sex']").val(list[item]);
                                }
                                if (item == 'schoolId') {
                                    $("#Form select[name='schoolId']").val(list[item]);
                                }
                                $("#Form input[name='" + item + "']").val(list[item]);
                            }
                            if (!empty(list.tags)) {
                                selectTags(list.tags);
                            }
                            $("#Form input[name='oldImgId']").val(oldImgId);
                            $("#Form").data('bootstrapValidator').destroy();
                            $('#Form').data('bootstrapValidator', null);
                            Validator();
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        // 添加
        add:function () {
            var that = this;
            $("#articleContent").val(editor.txt.html());
            var param = {};
            $("#Form").find('input,textarea,select').each(function(){
                param[$(this).attr('name')] = $(this).val();
            });
            // 得到标签
            var tagArr = $("#tags").val();
            var ids = "";
            if (!empty(tagArr)) {
                for (let i = 0; i < tagArr.length; i++) {
                    ids += tagArr[i];
                    if ((i + 1) != tagArr.length) {
                        ids += ",";
                    }
                }
            }
            param['tags'] = ids;
            param['companyId'] = companyId;
            // console.log(param)
            Post(that,_HOST+_API.organization_teacher_add,param,true,that.permissions[0])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if(response){
                        if(response.success){
                            layer.msg(response.msg, {time: 1500, icon:1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        // 修改
        update:function () {
            var that = this;
            $("#articleContent").val(editor.txt.html());
            var param = {};
            $("#Form").find('input,textarea,select').each(function(){
                param[$(this).attr('name')] = $(this).val();
            });
            // 得到标签
            var tagArr = $("#tags").val();
            var ids = "";
            if (!empty(tagArr)) {
                for (let i = 0; i < tagArr.length; i++) {
                    ids += tagArr[i];
                    if ((i + 1) != tagArr.length) {
                        ids += ",";
                    }
                }
            }
            param['tags'] = ids;
            param['companyId'] = companyId;
            // console.log(param)
            Post(that,_HOST+_API.organization_teacher_update,param,true,that.permissions[1])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if(response){
                        if(response.success){
                            layer.msg(response.msg, {time: 1500, icon:1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
    },
});

// 初始化多选
function initSelect(datas) {
    var select = $("#tags");
    for (var i = 0; i < datas.length; i++) {
        select.append("<option value='" + datas[i].id + "'>"
            + datas[i].name + "</option>");
    }
    select.selectpicker('val', '');
    select.selectpicker('refresh');
}
// 选中tag
function selectTags(value) {
    var s = document.getElementById("tags");
    console.log(value);
    if (!empty(value)) {
        var tagsArr = value.split(",");
        $('.selectpicker').selectpicker('val', tagsArr);
    }
}

function initFileUpload (url) {
    console.log(url);
    $("#fileUploadBtn").fileinput('destroy');
    $("#fileUploadBtn").fileinput({
        language: "zh",
        uploadUrl: _HOST+_API.common_file_ossUpload,
        ajaxSettings:{
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': ''
            }
        },
        browseClass: "btn btn-success",
        browseLabel: "上传预览图片",
        browseIcon: "<i class=\"glyphicon glyphicon-picture\"></i> ",
        allowedFileExtensions: ['jpg', 'gif', 'png'],
        showUpload: false,
        dropZoneEnabled: true,
        showPreview: true,
        minFileCount: 1,
        maxFileCount: 1,
        initialPreviewAsData: true,
        initialPreview: [
            url
        ],
        initialPreviewConfig: [
            {
                caption: url,
                size: 329892,
                width: "120px",
                url: url,
                key: 1
            },
        ]
    }).on("filebatchselected", function (event, files) {
        $(this).fileinput("upload");
    }).on("fileuploaded", function (event, data, previewId, index) {
        if (data.response.status) {
            $(".file-caption-name").text(data.response.attachemId);
            $("#articleImg").val(data.response.attachemId);
        } else {
            parent.layer.msg(data.response.msg, {time: 1500, icon: 5});
        }
    });
    $(".kv-file-remove").remove();
}

$(function () {
    editor.customConfig.uploadImgServer = _HOST+_API.common_file_ossWe;
    editor.customConfig.uploadFileName = 'file';
    editor.customConfig.uploadImgHeaders = {
        'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
        'permCoding': '',
        'enctype': 'multipart/form-data'
    };
    editor.customConfig.zIndex = 100;
    editor.create();

    if(empty(aGET.id)){
        initFileUpload('');
    }
});

$('#Form').data('bootstrapValidator', null);
Validator();
function Validator() {
    $('#Form').bootstrapValidator({
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '名字不能为空'
                    },
                    stringLength: {
                        max: 50,
                        message: '名字长度最多100个字符（一个汉字占两个字符）'
                    },
                }
            },
            wxTel: {
                validators: {
                    notEmpty: {
                        message: '请输入微信关联电话'
                    },
                    stringLength: {
                        max: 15,
                        message: '长度最多15个字符（一个汉字占两个字符）'
                    },
                }
            },
        }
    }).on('success.form.bv', function (e) {
        // Prevent form submission
        e.preventDefault();
        if(empty(aGET.id)){
            app.add();
        }else {
            app.update();
        }
    });
}
